package cn.itzzx.lagou.framework.servlet;

import cn.itzzx.lagou.framework.annotation.*;
import cn.itzzx.lagou.framework.pojo.Handler;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.net.URL;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 入口类
 * @author Martin
 * @since 1.0
 */
public class LgDispatcherServlet extends HttpServlet {


    private Properties properties = new Properties();

    private List<String> classNames = new LinkedList<>();

    private static Map<String, Object> ioc = new ConcurrentHashMap<>(256);

    private List<Handler> handlerMapping = new ArrayList<>();

    @Override
    public void init(ServletConfig config) throws ServletException {
        //1 加载配置文件， 获取包名
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        doLoadConfig(contextConfigLocation);

        //2 扫描相关的类，扫描注解
        doScanner(properties.getProperty("scannerPackage"));

        //3 初始化bean对象（实现ioc容器，基于注解）
        doInstance();

        //4 实现依赖注入
        doAutowire();

        //5 构造一个 HandlerMapping 处理器，将配置好的url和method建立映射关系
        initHandlerMapping();

        System.out.println("mvc init 完成");
    }

    private void initHandlerMapping() {

        if (ioc.isEmpty()) {
            return;
        }

        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            // 获取ioc中当前遍历的对象的class类型
            Class<?> aClass = entry.getValue().getClass();

            if (!aClass.isAnnotationPresent(LagouController.class)) {
                continue;
            }

            String baseUrl = "";
            //使用 Set 便于去除重复的认证用户
            Set<String> authUsers = new LinkedHashSet<>();
            if (aClass.isAnnotationPresent(LagouRequestMapping.class)) {
                LagouRequestMapping annotation = aClass.getAnnotation(LagouRequestMapping.class);
                // 等同于/demo
                baseUrl = annotation.value();
            }


            // 获取方法
            Method[] methods = aClass.getMethods();
            for (int i = 0; i < methods.length; i++) {
                Method method = methods[i];

                //  方法没有标识LagouRequestMapping，就不处理
                if (!method.isAnnotationPresent(LagouRequestMapping.class)) {
                    continue;
                }

                // 如果标识，就处理
                LagouRequestMapping annotation = method.getAnnotation(LagouRequestMapping.class);
                String methodUrl = annotation.value();  // /query
                String url = baseUrl +methodUrl;    // 计算出来的url /demo/query

                // 把method所有信息及url封装为一个Handler
                Handler handler = new Handler(entry.getValue(), method, Pattern.compile(url));

                // 计算方法的参数位置信息  // query(HttpServletRequest request, HttpServletResponse response,String name)
                Parameter[] parameters = method.getParameters();
                for (int j = 0; j < parameters.length; j++) {
                    Parameter parameter = parameters[j];

                    if (parameter.getType() == HttpServletRequest.class || parameter.getType() == HttpServletResponse.class) {
                        // 如果是request和response对象，那么参数名称写HttpServletRequest和HttpServletResponse
                        handler.getParamIndexMapping().put(parameter.getType().getSimpleName(), j);
                    } else {
                        handler.getParamIndexMapping().put(parameter.getName(), j);  // <name,2>
                    }
                }
                // 建立url和method之间的映射关系（map缓存起来）
                handlerMapping.add(handler);
            }
        }
    }

    private void doAutowire() {
        ioc.forEach((k, v) -> {
            //获取所有属性
            Field[] declaredFields = v.getClass().getDeclaredFields();
            for (Field declaredField : declaredFields) {
                //属性是否有 @Autowired 注解
                if (declaredField.isAnnotationPresent(LagouAutowire.class)) {
                    declaredField.setAccessible(true);
                    //获取注解中的value
                    String value = declaredField.getAnnotation(LagouAutowire.class).value();
                    //如果没有 使用属性名
                    if (value == null || "".equals(value)) {
                        value = declaredField.getName();
                    }
                    //从beanDefinitionMap找到对应的类赋值
                    try {
                        declaredField.set(value, ioc.get(value));
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private void doInstance() {
        if (classNames.isEmpty()) {
            return;
        }
        for (String className : classNames) {
            Class<?> clazz = null;
            try {
                clazz = Class.forName(className);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

            if (clazz.isAnnotationPresent(LagouController.class) || clazz.isAnnotationPresent(LagouService.class)) {
                String beanName = clazz.getDeclaredAnnotation(LagouController.class).value();
                if (beanName == null || "".equals(beanName)) {
                    // beanName 首字母小写
                    beanName = lowerFirst(clazz.getSimpleName());
                }
                try {
                    ioc.put(beanName, clazz.getDeclaredConstructor().newInstance());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 扫描类
     */
    private void doScanner(String scannerPackage) {

        //将. 转换 /
        //将 cn.itzzx.transfer 转换为 /cn/itzzx/transfer
        URL url = this.getClass().getClassLoader().getResource(scannerPackage.replaceAll("\\.", "/"));
        if(url == null){
            System.err.println(scannerPackage + " not found");;
            return;
        }
        File directory = new File(url.getFile());
        for (File file : directory.listFiles()) {
            //判断当前文件是否为文件夹，如果是继续递归调用
            if (file.isDirectory()) { //子包 package
                doScanner(scannerPackage + "." + file.getName());
            } else {
                //拿到 className
                String beanName = scannerPackage + "." + file.getName().replace(".class", "");
                classNames.add(beanName);
            }
        }

    }

    private void doLoadConfig(String contextConfigLocation) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //接收处理请求
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理请求：根据url，找到对应的Method方法，进行调用

        // 根据uri获取到能够处理当前请求的hanlder（从handlermapping中（list））
        Handler handler = getHandler(req);

        if(handler == null) {
            resp.getWriter().write("404 not found");
            return;
        }

        // 参数绑定
        // 获取所有参数类型数组，这个数组的长度就是我们最后要传入的args数组的长度
        Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();


        // 根据上述数组长度创建一个新的数组（参数数组，是要传入反射调用的）
        Object[] paraValues = new Object[parameterTypes.length];

        // 以下就是为了向参数数组中塞值，而且还得保证参数的顺序和方法中形参顺序一致

        Map<String, String[]> parameterMap = req.getParameterMap();

        String authValue = "";
        // 遍历request中所有参数  （填充除了request，response之外的参数）
        for(Map.Entry<String,String[]> param: parameterMap.entrySet()) {
            // name=1&name=2   name [1,2]
            String value = StringUtils.join(param.getValue(), ",");  // 如同 1,2

            // 如果参数和方法中的参数匹配上了，填充数据
            if(!handler.getParamIndexMapping().containsKey(param.getKey())) {continue;}

            // 方法形参确实有该参数，找到它的索引位置，对应的把参数值放入paraValues
            Integer index = handler.getParamIndexMapping().get(param.getKey());//name在第 2 个位置

            paraValues[index] = value;  // 把前台传递过来的参数值填充到对应的位置去

            //取当前请求username的参数
            if("username".equals(param.getKey())){
                authValue = value;
            }
        }

        //安全校验， 判断该当前请求的用户是否有权限访问
        boolean authority = isAuthority(handler, authValue);
        if(!authority){
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("["+authValue+"] 用户没有权限访问该请求");
            return;
        }


        //HttpServletRequest & HttpServletResponse赋值
        int requestIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName());
        paraValues[requestIndex] = req;

        int responseIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName());
        paraValues[responseIndex] = resp;

        // 最终调用handler的method属性
        try {
            handler.getMethod().invoke(handler.getController(),paraValues);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    private Handler getHandler(HttpServletRequest req) {
        if(handlerMapping.isEmpty()){return null;}
        String url = req.getRequestURI();
        for(Handler handler: handlerMapping) {
            Matcher matcher = handler.getPattern().matcher(url);
            if(!matcher.matches()){continue;}
            return handler;
        }
        return null;
    }

    /**
     * 首字母转换小写
     *
     * @param str
     * @return
     */
    private String lowerFirst(String str) {
        char[] chars = str.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }


    private boolean isAuthority(Handler handler,String authValue){
        Class<?> targetClass = handler.getController().getClass();

        //获取类上是否标注 @Security
        if(targetClass.isAnnotationPresent(Security.class)){
            Security annotation = targetClass.getAnnotation(Security.class);
            for (String authUser : annotation.value()) {
                if(authUser.equals(authValue)){
                    return true;
                }
            }
        }else if(handler.getMethod().isAnnotationPresent(Security.class)){
            Security securityAnnotation = handler.getMethod().getAnnotation(Security.class);
            for (String authUser : securityAnnotation.value()) {
                if(authUser.equals(authValue)){
                    return true;
                }
            }
        }
        return false;
    }
}
